package com.hujie.sqlqueryes.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 用户上下文持有者，使用ThreadLocal存储当前线程的用户ID
 */
@Component
public class UserContext {
    
    private static final Logger logger = LoggerFactory.getLogger(UserContext.class);
    
    private static final ThreadLocal<String> userIdHolder = new ThreadLocal<>();
    
    /**
     * 设置当前线程的用户ID
     * @param userId 用户ID
     */
    public static void setUserId(String userId) {
        userIdHolder.set(userId);
    }
    
    /**
     * 获取当前线程的用户ID
     * @return 用户ID
     */
    public static String getUserId() {
        return userIdHolder.get();
    }
    
    /**
     * 清除当前线程的用户ID
     */
    public static void clear() {
        String userId = userIdHolder.get();
        if (userId != null) {
            logger.debug("清理用户上下文，用户ID: {}", userId);
        }
        userIdHolder.remove();
    }
}